import { store } from '@/store'
import { defineStore } from 'pinia'
import { getAccessToken, removeToken } from '@/utils/auth'
import { CACHE_KEY, useCache, deleteUserCache } from '@/hooks/web/useCache'
import { getInfo, loginOut } from '@/api/login'
import { getPermissionInfo, portalLogout, AuditCount } from '@/api/portal'

const { wsCache } = useCache()

interface UserVO {
  id: number
  avatar: string
  nickname: string
  deptId: number
}

// 更新门户权限信息接口，匹配实际返回的数据结构
export interface PortalPermissionInfo {
  id: string | number
  name: string
  telePhone?: string
  email?: string
  nickName?: string
  permissions?: string[]
  roles?: string[]
  menus?: any[]
}

interface UserInfoVO {
  permissions: Set<string>
  roles: string[]
  isSetUser: boolean
  user: UserVO
  portalUser: PortalPermissionInfo // 重命名为更清晰的命名
  auditCount: number // 添加审核数量状态
}

export const useUserStore = defineStore('admin-user', {
  state: (): UserInfoVO => ({
    permissions: new Set<string>(),
    roles: [],
    isSetUser: false,
    user: {
      id: 0,
      avatar: '',
      nickname: '',
      deptId: 0
    },
    portalUser: {
      id: '',
      name: '',
      telePhone: '',
      email: ''
    },
    auditCount: 0 // 初始化审核数量为0
  }),
  getters: {
    getPermissions(): Set<string> {
      return this.permissions
    },
    getRoles(): string[] {
      return this.roles
    },
    getIsSetUser(): boolean {
      return this.isSetUser
    },
    getUser(): UserVO {
      return this.user
    },
    getPortalUser(): PortalPermissionInfo {
      return this.portalUser
    },
    getAuditCount(): number {
      return this.auditCount
    }
  },
  actions: {
    async setUserInfoAction() {
      if (!getAccessToken()) {
        this.resetState()
        throw new Error('Token不存在，请重新登录')
      }

      let userInfo = wsCache.get(CACHE_KEY.USER)
      if (!userInfo) {
        // 使用门户接口获取用户信息
        try {
          userInfo = await getPermissionInfo()
        } catch (error) {
          console.warn('获取用户信息失败', error)
          throw new Error('获取用户信息失败，请重新登录')
        }
      } else {
        try {
          // 刷新用户信息
          userInfo = await getPermissionInfo()
        } catch (error) {
          console.warn('获取用户信息失败，使用缓存数据', error)
          throw new Error('获取用户信息失败，请重新登录')
        }
      }

      // 适配门户接口返回的数据结构
      this.permissions = new Set(userInfo.permissions || [])
      this.roles = userInfo.roles || []

      // 更新用户信息，兼容新旧数据结构
      this.user = {
        id: Number(userInfo.id) || 0,
        avatar: userInfo.avatar || '',
        nickname: userInfo.name || userInfo.nickName || '',
        deptId: 0
      }

      // 存储完整的门户用户信息
      this.portalUser = userInfo
      this.isSetUser = true

      // 缓存用户信息
      wsCache.set(CACHE_KEY.USER, userInfo)
      wsCache.set(CACHE_KEY.ROLE_ROUTERS, userInfo.menus || [])
    },

    // 新增：专门处理门户用户信息的方法
    async setPortalUserInfoAction(userInfo: PortalPermissionInfo) {
      this.portalUser = userInfo

      // 同步更新到用户基本信息
      this.user = {
        id: Number(userInfo.id) || 0,
        avatar: '',
        nickname: userInfo.name || userInfo.nickName || '',
        deptId: 0
      }

      this.isSetUser = true

      // 缓存门户用户信息
      wsCache.set(CACHE_KEY.USER, userInfo)
      wsCache.set(CACHE_KEY.ROLE_ROUTERS, userInfo.menus || [])
    },

    async setUserAvatarAction(avatar: string) {
      const userInfo = wsCache.get(CACHE_KEY.USER)
      if (userInfo) {
        this.user.avatar = avatar
        userInfo.avatar = avatar
        wsCache.set(CACHE_KEY.USER, userInfo)
      }
    },

    async setUserNicknameAction(nickname: string) {
      const userInfo = wsCache.get(CACHE_KEY.USER)
      if (userInfo) {
        this.user.nickname = nickname
        userInfo.nickname = nickname
        wsCache.set(CACHE_KEY.USER, userInfo)
      }
    },

    async loginOut() {
      try {
        // await loginOut()
        await portalLogout()
      } catch (error) {
        console.warn('退出登录接口调用失败', error)
      }
      removeToken()
      deleteUserCache()
      this.resetState()
    },

    async updateAuditCountAction() {
      try {
        const res = await AuditCount()
        this.auditCount = res > 0 ? res : 0
      } catch (error) {
        console.error('获取审核数量失败:', error)
        this.auditCount = 0
      }
    },

    resetAuditCount() {
      this.auditCount = 0
    },

    resetState() {
      this.permissions = new Set<string>()
      this.roles = []
      this.isSetUser = false
      this.user = {
        id: 0,
        avatar: '',
        nickname: '',
        deptId: 0
      }
      this.portalUser = {
        id: '',
        name: '',
        telePhone: '',
        email: ''
      }
    }
  }
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
